﻿using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
    
    public class FrameStationChangeMaterialConfirmationQueryController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] FrameStationChangeMaterialConfirmationQuery FSCMCQ)
        {
            ReturnObjectQuery RO = new ReturnObjectQuery();
            if (FSCMCQ.PageNumber <= 0 || FSCMCQ.PageSize <= 0)
            {
               
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "分页参数无效";
                RO.Data = null;
                Logger.Error("分页参数无效");
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
                {
                    await connection.OpenAsync();

                    var whereClause = "WHERE 1=1";
                    if (FSCMCQ.FSCMC_ID != 0)
                    {
                        whereClause += " AND FSCMCID = @ID";
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_OperatorConfirmation))
                    {
                        whereClause += " AND FSCMCOperatorConfirmation LIKE @OperatorConfirmation";
                    }
                    if (FSCMCQ.FSCMC_ConfirmationTime.HasValue)
                    {
                        whereClause += " AND FSCMCConfirmationTime = @ConfirmationTime";
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_ProductModel))
                    {
                        whereClause += " AND FSCMCProductModel LIKE @ProductModel";
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_LineParting))
                    {
                        whereClause += " AND FSCMCLineParting LIKE @LineParting";
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_PartCompliance))
                    {
                        whereClause += " AND FSCMCPartCompliance LIKE @PartCompliance";
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_FrameLOGOPosition))
                    {
                        whereClause += " AND FSCMCFrameLOGOPosition LIKE @FrameLOGOPosition";
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_FrameColor))
                    {
                        whereClause += " AND FSCMCFrameColor LIKE @FrameColor";
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_ButtonLOGOPosition))
                    {
                        whereClause += " AND FSCMCButtonLOGOPosition LIKE @ButtonLOGOPosition";
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_ButtonColor))
                    {
                        whereClause += " AND FSCMCButtonColor LIKE @ButtonColor";
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_FluorescentParticleColor))
                    {
                        whereClause += " AND FSCMCFluorescentParticleColor LIKE @FluorescentParticleColor";
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_NonconformanceDescriptionIfAny))
                    {
                        whereClause += " AND FSCMCNonconformanceDescriptionIfAny LIKE @NonconformanceDescriptionIfAny";
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_NonconformanceImage))
                    {
                        whereClause += " AND FSCMCNonconformanceImage LIKE @NonconformanceImage";
                    }

                    var query = $@"
                        SELECT 
                            FSCMCID, FSCMCOperatorConfirmation, FSCMCConfirmationTime, FSCMCProductModel, 
                            FSCMCLineParting, FSCMCPartCompliance, FSCMCFrameLOGOPosition, FSCMCFrameColor, 
                            FSCMCButtonLOGOPosition, FSCMCButtonColor, FSCMCFluorescentParticleColor, 
                            FSCMCNonconformanceDescriptionIfAny, FSCMCNonconformanceImage,
                            COUNT(*) OVER() AS TotalCount
                        FROM 
                            (SELECT 
                                FSCMCID, FSCMCOperatorConfirmation, FSCMCConfirmationTime, FSCMCProductModel, 
                                FSCMCLineParting, FSCMCPartCompliance, FSCMCFrameLOGOPosition, FSCMCFrameColor, 
                                FSCMCButtonLOGOPosition, FSCMCButtonColor, FSCMCFluorescentParticleColor, 
                                FSCMCNonconformanceDescriptionIfAny, FSCMCNonconformanceImage,
                                ROW_NUMBER() OVER(ORDER BY FSCMCID) AS RowNum
                             FROM FrameStationChangeMaterialConfirmation {whereClause}) AS Result
                        WHERE 
                            RowNum BETWEEN @StartRow AND @EndRow
                        ORDER BY RowNum";

                    int startRow = (FSCMCQ.PageNumber - 1) * FSCMCQ.PageSize + 1;
                    int endRow = FSCMCQ.PageNumber * FSCMCQ.PageSize;

                    var parameters = new List<SqlParameter>
                    {
                        new SqlParameter("@StartRow", SqlDbType.Int) { Value = startRow },
                        new SqlParameter("@EndRow", SqlDbType.Int) { Value = endRow }
                    };
                    if (FSCMCQ.FSCMC_ID != 0)
                    {
                        parameters.Add(new SqlParameter("@ID", SqlDbType.Int) { Value = FSCMCQ.FSCMC_ID });
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_OperatorConfirmation))
                    {
                        parameters.Add(new SqlParameter("@OperatorConfirmation", SqlDbType.NVarChar, 50) { Value = $"%{FSCMCQ.FSCMC_OperatorConfirmation}%" });
                    }
                    if (FSCMCQ.FSCMC_ConfirmationTime.HasValue)
                    {
                        parameters.Add(new SqlParameter("@ConfirmationTime", SqlDbType.DateTime) { Value = FSCMCQ.FSCMC_ConfirmationTime.Value });
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_ProductModel))
                    {
                        parameters.Add(new SqlParameter("@ProductModel", SqlDbType.NVarChar, 50) { Value = $"%{FSCMCQ.FSCMC_ProductModel}%" });
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_LineParting))
                    {
                        parameters.Add(new SqlParameter("@LineParting", SqlDbType.NVarChar, 50) { Value = $"%{FSCMCQ.FSCMC_LineParting}%" });
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_PartCompliance))
                    {
                        parameters.Add(new SqlParameter("@PartCompliance", SqlDbType.NVarChar, 50) { Value = $"%{FSCMCQ.FSCMC_PartCompliance}%" });
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_FrameLOGOPosition))
                    {
                        parameters.Add(new SqlParameter("@FrameLOGOPosition", SqlDbType.NVarChar, 50) { Value = $"%{FSCMCQ.FSCMC_FrameLOGOPosition}%" });
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_FrameColor))
                    {
                        parameters.Add(new SqlParameter("@FrameColor", SqlDbType.NVarChar, 50) { Value = $"%{FSCMCQ.FSCMC_FrameColor}%" });
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_ButtonLOGOPosition))
                    {
                        parameters.Add(new SqlParameter("@ButtonLOGOPosition", SqlDbType.NVarChar, 50) { Value = $"%{FSCMCQ.FSCMC_ButtonLOGOPosition}%" });
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_ButtonColor))
                    {
                        parameters.Add(new SqlParameter("@ButtonColor", SqlDbType.NVarChar, 50) { Value = $"%{FSCMCQ.FSCMC_ButtonColor}%" });
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_FluorescentParticleColor))
                    {
                        parameters.Add(new SqlParameter("@FluorescentParticleColor", SqlDbType.NVarChar, 50) { Value = $"%{FSCMCQ.FSCMC_FluorescentParticleColor}%" });
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_NonconformanceDescriptionIfAny))
                    {
                        parameters.Add(new SqlParameter("@NonconformanceDescriptionIfAny", SqlDbType.NVarChar, 100) { Value = $"%{FSCMCQ.FSCMC_NonconformanceDescriptionIfAny}%" });
                    }
                    if (!string.IsNullOrEmpty(FSCMCQ.FSCMC_NonconformanceImage))
                    {
                        parameters.Add(new SqlParameter("@NonconformanceImage", SqlDbType.NVarChar, 100) { Value = $"%{FSCMCQ.FSCMC_NonconformanceImage}%" });
                    }

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters.ToArray());
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                Logger.Warn("未找到记录");
                                RO.Status = HttpStatusCode.NotFound;
                                RO.Message = "未找到记录";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                            }

                            var products = new List<FrameStationChangeMaterialConfirmation>();
                            int totalCount = 0;
                            while (await reader.ReadAsync())
                            {
                                if (totalCount == 0)
                                {
                                    totalCount = reader.GetInt32(reader.GetOrdinal("TotalCount"));
                                }

                                products.Add(new FrameStationChangeMaterialConfirmation
                                {
                                    FSCMC_ID = reader.GetInt32(reader.GetOrdinal("FSCMCID")),
                                    FSCMC_OperatorConfirmation = reader.GetString(reader.GetOrdinal("FSCMCOperatorConfirmation")),
                                    FSCMC_ConfirmationTime = reader.GetDateTime(reader.GetOrdinal("FSCMCConfirmationTime")),
                                    FSCMC_ProductModel = reader.GetString(reader.GetOrdinal("FSCMCProductModel")),
                                    FSCMC_LineParting = reader.GetString(reader.GetOrdinal("FSCMCLineParting")),
                                    FSCMC_FrameLOGOPosition = reader.GetString(reader.GetOrdinal("FSCMCFrameLOGOPosition")),
                                    FSCMC_FrameColor = reader.GetString(reader.GetOrdinal("FSCMCFrameColor")),
                                    FSCMC_ButtonLOGOPosition = reader.GetString(reader.GetOrdinal("FSCMCButtonLOGOPosition")),
                                    FSCMC_ButtonColor = reader.GetString(reader.GetOrdinal("FSCMCButtonColor")),
                                    FSCMC_FluorescentParticleColor = reader.GetString(reader.GetOrdinal("FSCMCFluorescentParticleColor")),
                                    FSCMC_NonconformanceDescriptionIfAny = reader.GetString(reader.GetOrdinal("FSCMCNonconformanceDescriptionIfAny")),
                                    FSCMC_NonconformanceImage = reader.GetString(reader.GetOrdinal("FSCMCNonconformanceImage"))
                                });
                            }

                            Logger.Info("查询成功");
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "OK";
                            RO.Data = products;
                            RO.TotalCount = totalCount;
                            RO.PageNumber = FSCMCQ.PageNumber;
                            RO.PageSize = FSCMCQ.PageSize;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("查询失败: " + ex.Message);
                RO.Status = HttpStatusCode.InternalServerError;
                RO.Message = "Error: " + ex.Message;
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
            }
        }
    }
}
